from flask_jwt_extended import (

    get_jwt_identity
)
from flask import jsonify, request
from flask_jwt_extended import  get_jwt_identity
from app.models import *
import time
from app.auth.login import*
import jwt

def uploadData():
    receivedTime = int(time.time())
    
    data = request.get_json()
    access_token = data.get('token')
        # valid = validate_required(data, ['data', 'token'])
        # if not valid:
    if data is None or not isinstance(data, dict) or not data: # 以后再说
            return jsonify(
                code=201, 
                msg="缺少参数",
                data={'receivedTime': receivedTime}
            ), 200
        
    device = data.get('deviceId') # 设备ID
        # 设备身份验证
    if not get_device(device):
            return jsonify(
                code=202,
                msg="未知设备ID",
                data={'receivedTime': receivedTime}         
            ), 200
            
          
    try:
        data = request.get_json()
        access_token = data.get('token')     
        decoded_payload = jwt.decode(access_token, algorithms=["HS256"])
        expired_time = decoded_payload.get("expiredTime")  # 获取过期时间戳

        if expired_time:
            health_data = data['data']
        high=int (health_data.get('high'))
        low=int (health_data.get('low'))
        if high<low:
            return jsonify(
                code=205,
                msg="血压值不正确",
                data={'receivedTime': receivedTime}
            ), 200
        # 数据存储  
        record_time = datetime.fromtimestamp(health_data['time'])
        new_record = HealthData(
        
                    user_id=get_id_by_device_id(device),
                    timestamp=record_time,
                    high=health_data['high'],
                    low=health_data['low'],
                    heartbeat=health_data.get('heartbeat'),
                    breathe=health_data.get('breathe'),
                    walkpace=health_data.get('walkpace'),
                    consume = health_data.get('consume'),
                    sleeptime = health_data.get('sleeptime')
                    
                )
        db.session.add(new_record)
        db.session.commit()


        return jsonify(
                code=200,
                message="成功",
            ),200
    except jwt.ExpiredSignatureError:
        return jsonify(
                code=206,
                msg="token过期",
            ), 200
    except jwt.InvalidTokenError:
        return jsonify(
                code=20,
                msg="token无效",
                
            ), 200


                
           


    